package com.sfy.mallchat.common.common.aspect;

import com.sfy.mallchat.common.common.annotation.RedissonLock;
import com.sfy.mallchat.common.common.service.LockService;
import com.sfy.mallchat.common.common.utils.SpElUtil;
import jodd.util.StringUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.junit.jupiter.api.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@Aspect
@Order(0)//确保比事务注解先执行，分布式锁在事务外
public class RedisLockAspect {

    @Autowired
    private LockService lockService;

    @Around("@annotation(redissonLock)")
    public Object around(ProceedingJoinPoint joinPoint, RedissonLock redissonLock) throws Throwable{
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        String prefix = StringUtil.isBlank(redissonLock.prefixKey())?redissonLock.prefixKey(): SpElUtil.getMethodKey(method);
        String key = SpElUtil.parseSpEl(method,joinPoint.getArgs(),redissonLock.key());
        return lockService.excuteWithLock(prefix+":"+key, redissonLock.waitTime()
                , redissonLock.unit(), joinPoint::proceed);
    }
}
